package com.haoshuang.zhouzhoubang.ui.page.order.rework.rework.team

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.ActivityTeamReworkBinding
import com.haoshuang.zhouzhoubang.model.bean.RenWuBean
import com.haoshuang.zhouzhoubang.model.bean.YyBean
import com.haoshuang.zhouzhoubang.ui.dialog.ConfirmDialog
import com.haoshuang.zhouzhoubang.ui.page.order.assignment.TaskAssignmentActivity
import com.haoshuang.zhouzhoubang.ui.page.order.rework.rework.compensate.CompensateActivity
import com.haoshuang.zhouzhoubang.ui.page.order.time.UpdateServiceTimeActivity
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.core.setOnItemChildClick
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.callPhone
import com.mufeng.libs.utils.ktx.fromJson
import com.mufeng.libs.utils.ktx.fromJsonToList
import com.mufeng.libs.utils.ktx.getString
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.startPageForResult
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.gone
import com.mufeng.libs.utils.view.load
import com.mufeng.libs.utils.view.visible

/**
 *  门店返工单
 */
class TeamReworkActivity : BaseVMActivity<TeamReworkViewModel, ActivityTeamReworkBinding>() {

    companion object {
        fun launch(context: Context){
            context.startPage<TeamReworkActivity>()
        }
    }


    private var members: List<RenWuBean.TeamMemberData>? = null
    private var member: RenWuBean.TeamMemberData? = null
    private var orderId = ""

    var service_day = ""
    var service_time = ""

    lateinit var adapter3: TeamListAdapter
    var list3 = arrayListOf<YyBean.ThirdInfo.TeamUser>()

    var user_status = ""
    var gson = Gson()


    var user_phone = ""
    var user_phone2 = ""
    var user_id9 = ""
    var cate_id = ""
    var list6 = arrayListOf<YyBean.ThirdInfo.TeamUser>()

    // 分配的负责人ID
    private var teamUserId = ""
    // 分配的成员id
    private var memberIds = ""

    override fun initView(savedInstanceState: Bundle?) {
        orderId = intent.getString("order_id")
        binding.titleBar.title = "返工处理"
        binding.titleBar.leftImageView().click { finish() }

        val lay2 = LinearLayoutManager(this)
        lay2.orientation = LinearLayoutManager.HORIZONTAL
        binding.rvList3.layoutManager = lay2
        adapter3 = TeamListAdapter(list3)

        binding.llAdd.clickWithTrigger {
            var str = gson.toJson(list6)
            startPageForResult<TaskAssignmentActivity>(
                "ids" to orderId, "user_id9" to user_id9, "bean" to str, "returnResult" to true
            ){code, data ->
                if (code == 200){
                    member = data?.getStringExtra("member")?.fromJson<RenWuBean.TeamMemberData>()
                    if (member != null) {
                        binding.tvAdd.load(member?.avatar, R.mipmap.rl)

                        user_id9 = member?.to_user_id.toString()
                        binding.tvAdd2.visible()
                        binding.callPhone2.visible()

                        teamUserId = member!!.to_user_id.toString()
                    } else {
                        binding.tvAdd2.gone()
                        binding.callPhone2.gone()
                    }

                    members = data?.getStringExtra("members")?.fromJsonToList<RenWuBean.TeamMemberData>()
                    val list = members?.map {
                        YyBean.ThirdInfo.TeamUser(
                            order_id = orderId.toString(),
                            user_id = it.to_user_id.toString(),
                            nickname = it.nickname,
                            avatar = it.avatar,
                            phone = ""
                        )
                    }?.toMutableList()
                    list3.clear()
                    list6.clear()
                    list3.addAll(list ?: emptyList())
                    list6.addAll(list ?: emptyList())
                    list3.add(YyBean.ThirdInfo.TeamUser("", "", "", "", ""))
                    adapter3.notifyDataSetChanged()
                    memberIds = list6.joinToString(","){it.user_id}
                }
            }
        }

        binding.rvList3.adapter = adapter3

        binding.callPhone.clickWithTrigger {
            if (user_phone.isNullOrBlank()) {
                toast("电话不能为空")
                return@clickWithTrigger
            }
            callPhone(user_phone)
        }

        adapter3.setOnItemChildClick(id = R.id.callPhone){view, position, item ->
            if (item?.phone.isNullOrBlank()) {
                toast("电话不能为空")
                return@setOnItemChildClick
            }
            callPhone(item?.phone?:"")
        }

        adapter3.setOnItemChildClick(id = R.id.tvAdd){view, position, item ->
            var str = gson.toJson(list6)
            startPageForResult<TaskAssignmentActivity>(
                "ids" to orderId, "user_id9" to user_id9, "bean" to str, "returnResult" to true
            ){code, data ->
                if (code == 200){
                    member = data?.getStringExtra("member")?.fromJson<RenWuBean.TeamMemberData>()
                    if (member != null) {
                        binding.tvAdd.load(member?.avatar, R.mipmap.rl)

                        user_id9 = member?.to_user_id.toString()
                        binding.tvAdd2.visible()
                        binding.callPhone2.visible()

                        teamUserId = member!!.to_user_id.toString()
                    } else {
                        binding.tvAdd2.gone()
                        binding.callPhone2.gone()
                    }

                    members = data?.getStringExtra("members")?.fromJsonToList<RenWuBean.TeamMemberData>()
                    val list = members?.map {
                        YyBean.ThirdInfo.TeamUser(
                            order_id = orderId.toString(),
                            user_id = it.to_user_id.toString(),
                            nickname = it.nickname,
                            avatar = it.avatar,
                            phone = ""
                        )
                    }?.toMutableList()
                    list3.clear()
                    list6.clear()
                    list3.addAll(list ?: emptyList())
                    list6.addAll(list ?: emptyList())
                    list3.add(YyBean.ThirdInfo.TeamUser("", "", "", "", ""))
                    adapter3.notifyDataSetChanged()
                    memberIds = list6.joinToString(","){it.user_id}
                }
            }
        }

        binding.llSm.clickWithTrigger {
            startPageForResult<UpdateServiceTimeActivity>("cate_id" to cate_id){code, data ->
                if (data != null) {
                    service_day = data.getStringExtra("service_day").toString()
                    var service_day1 = data.getStringExtra("service_day1")
                    service_time = data.getStringExtra("service_time").toString()
                    binding.tvTime.text = service_day1 + "     " + service_time
                }
            }
        }

        binding.callPhone2.clickWithTrigger {
            if (user_phone2.isNullOrBlank()) {
                toast("电话不能为空")
                return@clickWithTrigger
            }
            callPhone(user_phone2)
        }

        binding.tvRework.clickWithTrigger {
            if (service_day.isEmpty() || service_time.isEmpty()) {
                XPopup.Builder(this)
                    .asCustom(
                        ConfirmDialog(
                            context = this,
                            title = "温馨提示",
                            content = "请选择与客户协商的返工上门时间",
                            confirmStr = "我知道了",
                            isHideCancel = true,
                            onCancel = {},
                            onConfirm = {})
                    )
                    .show()
                return@clickWithTrigger
            }


            vm.masterAgreeRework(
                orderId,
                service_day,
                service_time,
                teamUserId,
                memberIds,
            )
        }

        binding.llCompensate.clickWithTrigger {
            startPageForResult<CompensateActivity>("order_id" to orderId){ code, data ->
                if (code == 200){
                    setResult(200)
                    finish()
                }
            }
        }
    }

    override fun initData() {
        vm.confirmOrderTime(orderId)
    }

    override fun startObserve() {
        vm.masterAgreeReworkData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                setResult(201)
                finish()
            }
        }

        vm.confirmOrderTimeData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {res ->
                val it = res?.data
                dismissLoading()
                if (it != null) {

                    binding.apply {
                        if (it.third_info.user_status == "1") {
                            tvAdd.visible()
                        } else {
                            tvAdd.gone()
                        }
                        realName.text = it.first_info.real_name
                        storeName.text = it.first_info.store_name
                        serviceTime.text = it.first_info.service_time
                        baseAddress.text = it.first_info.base_address
                        cate_id = it.first_info.cate_id
                        user_phone = it.first_info.user_real_phone
                        if (it.third_info.team_member.size > 0) {
                            list3.clear()
                            list6.clear()
                            list3.addAll(it.third_info.team_member)
                            list6.addAll(it.third_info.team_member)
                            if (it.third_info.user_status == "1") {
                                list3.add(YyBean.ThirdInfo.TeamUser("", "", "", "", ""))
                            }
                            adapter3.notifyDataSetChanged()
                            memberIds = list6.joinToString(","){it.user_id}
                        }
                        if (!it.third_info.team_leader.nickname.isNullOrBlank()) {
                            teamUserId = it.third_info.team_leader.user_id
                            tvAdd.load(it.third_info.team_leader.avatar, R.mipmap.rl)
                            user_phone2 = it.third_info.team_leader.phone
                            user_id9 = it.third_info.team_leader.user_id
                            tvAdd2.visible()
                            callPhone2.visible()
                        } else {
                            tvAdd2.gone()
                            callPhone2.gone()
                        }
                    }
                }
            }
        }
    }

}